<template>
  <container>
    <Title :level="3">请选择要识别动漫截图</Title>
    <Upload :fileList="[]" :showUploadList="false" accept="image/*" :before-upload="beforeUpload">
      <Input readonly placeholder="点击这里上传图片" :value="fileName">
        <template #addonAfter>
          <Button block :disabled="!file || quota===0 || quota-quotaUsed<=0" @click.stop="start"><span v-if="loading"><LoadingOutlined/>识别中</span><span
            v-else>开始识别</span></Button>
        </template>
      </Input>
    </Upload>
    <Paragraph>
      <blockquote>使用 trace.moe API，有使用次数限制。用户ID：
        <Text code>{{ id }}</Text>
        ，每月次数剩余：
        <Text code>{{ quota }}</Text>
        ，已使用次数：
        <Text code>{{ quotaUsed }}</Text>
      </blockquote>
    </Paragraph>
    <template v-if="file">
      <Divider/>
      <Title :level="3">预览</Title>
      <Image
        style="max-width: 100%"
        :src="file"
        fallback=""
      />
    </template>
    <template v-if="result.length>0">
      <Divider/>
      <Title :level="3">结果</Title>
      <template v-for="(item,index) in result" :key="index">
        <Divider/>
        <Descriptions :title="item.anilist.title.native + (item.episode ? ' EP#' + item.episode: '')" bordered size="small" layout="vertical">
          <Item label="罗马音">{{ item.anilist.title.romaji }}</Item>
          <Item label="文件名">{{ item.filename }}</Item>
          <Item label="相似度">{{ (item.similarity * 100).toFixed(2) + '%' }}</Item>
          <Item label="匹配位置">
            <Text code>{{ secondToDate(item.from) }}</Text>
            ~
            <Text code>{{ secondToDate(item.to) }}</Text>
          </Item>
          <Item label="预览" :span="3">
            <video controls style="max-width: 100%"
                   :src="item.video"
                   :poster="item.image"></video>
          </Item>
        </Descriptions>
      </template>
    </template>
  </container>
</template>

<script>
import Container from '@/components/container.vue'
import { Input, Upload, Typography, Button, Divider, Image, Descriptions } from 'ant-design-vue'
import { LoadingOutlined } from '@ant-design/icons-vue'

const { Item } = Descriptions
const { Title, Paragraph, Text } = Typography

export default {
  name: 'what_anime_is_this',
  components: {
    Container,
    Input,
    Upload,
    Title,
    Button,
    Divider,
    Image,
    Paragraph,
    Text,
    Descriptions,
    Item,
    LoadingOutlined
  },
  data: () => ({
    file: '',
    img: undefined,
    fileName: '',
    id: '',
    quota: 0,
    quotaUsed: 0,
    loading: false,

    result: []
  }),
  mounted () {
    this.checkTimes()
  },
  methods: {
    beforeUpload (img) {
      if (img.size / 1024 / 1024 >= 10) {
        this.$msg.error('图片大小不能超过10MB!')
        return false
      }
      const reader = new FileReader()
      reader.onload = () => {
        this.img = img
        this.fileName = img.name
        this.file = reader.result
      }
      reader.readAsDataURL(img)
      return false
    },
    async start () {
      try {
        this.loading = true
        const formData = new FormData()
        formData.append('image', this.img)
        const res = await this.$axios.post('https://api.trace.moe/search?anilistInfo', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        this.loading = false
        await this.checkTimes()
        if (!res.data.error) {
          this.result = res.data.result || []
        }
      } catch (e) {
        this.loading = false
        this.$msg.error('请求失败，请检查网络连接')
      }
    },
    async checkTimes () {
      try {
        const res = await this.$axios.get('https://api.trace.moe/me')
        this.id = res.data.id || ''
        this.quotaUsed = res.data.quotaUsed || 0
        this.quota = res.data.quota || 0
      } catch (e) {
        this.$msg.error('请求失败，请检查网络连接')
      }
    },
    secondToDate (seconds) {
      const h = Math.floor(seconds / 3600)
      const m = Math.floor((seconds / 60 % 60))
      const s = (seconds % 60).toFixed(2)
      return h + ':' + m + ':' + s
    }
  }
}
</script>

<style scoped lang="scss">
:deep(.ant-upload) {
  width: 100% !important;
}

:deep(.ant-input-group-addon) {
  padding: 0;
  border: unset;
}
</style>
